<template>
  <a-space direction="vertical">
    <a-card title="交易唯一性判断模板配置">
      <a-form ref="searchRef" name="searchBar" :model="searchFormState" :labelCol="{ span: 5, offset: 1 }"
        @finish="handleSearch">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item name="tempId" label="模板编号">
              <a-input v-model:value="searchFormState.tempId" placeholder=""></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="tempName" label="模板名称">
              <a-input v-model:value="searchFormState.tempName" placeholder=""></a-input>
            </a-form-item>
          </a-col>
          <!-- 新增：渠道名称下拉选择查询条件 -->
          <a-col :span="8" :offset="0">
            <a-form-item name="channelName" label="渠道名称">
              <a-select v-model:value="searchFormState.channelName" placeholder="请选择渠道名称" :loading="channelLoading"
                allowClear showSearch :filterOption="filterChannelByName">
                <a-select-option v-for="channel in channelList" :key="channel.transChannelName"
                  :value="channel.transChannelName">
                  {{ channel.transChannelName || '未命名渠道' }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>          
        </a-row>
        <a-row>
          <a-col :span="24" style="text-align: right">
            <a-button type="primary" html-type="submit" :loading="searchLoading">搜索</a-button>
            <a-button style="margin: 0 8px" @click="() => searchRef?.resetFields()">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <a-space>
        <a-button @click="showModal" type="primary"><template #icon> <appstore-add-outlined /> </template>新增</a-button>
        <!-- 新增配置要素按钮 -->
        <a-button @click="showFactorAddModal" type="primary" style="background-color: #1890ff"><template #icon>
            <usergroup-add-outlined /> </template>要素配置</a-button>
        <a-button @click="showEditModal"
          style="background-color: #f6ffed; color: #237804; border-color: #b7eb8f"><template #icon> <form-outlined />
          </template>修改</a-button>
        <a-button @click="showDelete" type="primary" danger><template #icon> <delete-outlined />
          </template>删除</a-button>
      </a-space>
    </a-card>
    <a-card title="查询结果">
      <a-table class="ant-table-striped" :rowClassName="
            (_record: any, index: number) => (index % 2 === 1 ? 'table-striped' : null)
          " :columns="columns" :data-source="data" rowKey="id" :loading="searchLoading" :rowSelection="rowSelection"
        @change="
            (pagination: any) => {
              handleSearch(pagination);
            }
          " :pagination="{
            position: [`bottomRight`],
            showSizeChanger: true,
            showQuickJumper: true,
            current: pageNum,
            pageSize,
            total: total,
            showTotal: (total: any) => `总计 ${total} 条记录`,
          }">
        <template #bodyCell="{ column, text }">
          <template v-if="column.dataIndex === 'name'">
            <a>{{ text }}</a>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal ref="modalRef" v-model:visible="visible" @ok="handleOk" style="width: 1200px; top: 0">
      <template #title>
        <div ref="modalTitleRef" style="width: 100%; cursor: move">
          {{ currentAction }}交易唯一性判断模板
        </div>
      </template>
      <a-form ref="formRef" :model="formState" :labelCol="{ span: 5, offset: 1 }" name="form_in_modal">
        <a-row :gutter="24">
          <a-col :span="14" :offset="6">
            <a-form-item name="channelId" label="渠道编号" :rules="[{ required: true, message: '请输入渠道编号' }]">
              <!-- 新增时显示可编辑选择器，编辑时显示只读文本 -->
              <template v-if="currentAction === action.add">
                <a-select v-model:value="formState.channelId" placeholder="请选择渠道编号" :loading="channelLoading" allowClear
                  showSearch
                  :filterOption="(inputValue: string, option: any) => filterChannel(inputValue, option, channelList)"
                  @change="(val: string) => handleChannelChange(val, channelList, formState)">
                  <!-- 遍历渠道编号列表生成选项 -->
                  <a-select-option v-for="channel in channelList" :key="channel.transChannelCode"
                    :value="channel.transChannelCode">
                    {{ channel.transChannelCode }} - {{ channel.transChannelName || '未命名组' }}
                  </a-select-option>
                </a-select>
              </template>
              <template v-else>
                <a-input v-model:value="formState.channelId" readonly
                  style="background-color: #f5f5f5; cursor: not-allowed;" />
              </template>
            </a-form-item>
          </a-col>
          <!-- 自动映射的组名称（只读显示） -->
          <a-col :span="14" :offset="6">
            <a-form-item name="channelName" label="渠道名称" :rules="[{ required: true, message: '渠道名称不能为空' }]">
              <a-input v-model:value="formState.channelName" placeholder="渠道编号后自动填充" readonly />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="14" :offset="6">
            <a-form-item name="tempId" label="模板编号" :rules="[{ required: true, message: '请输入模板编号' }]">
              <a-input v-model:value="formState.tempId" :readonly="currentAction === action.edit"
                :style="currentAction === action.edit ? 'background-color: #f5f5f5; cursor: not-allowed;' : ''" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="14" :offset="6">
            <a-form-item name="tempName" label="模板名称" :rules="[{ required: true, message: '请输入模板名称' }]">
              <a-input v-model:value="formState.tempName" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <!-- 配置要素新增弹窗（支持多选批量插入） -->
    <a-modal ref="factorModalRef" v-model:visible="factorVisible" @ok="handleFactorBatchOk"
      :title="`批量配置要素（模板：${selectedTemplateName}）`" style="width: 1000px; top: 20px"
      :body-style="{ maxHeight: '600px', overflowY: 'auto' }">
      <a-form ref="factorFormRef" :model="factorFormState" :labelCol="{ span: 6 }" :wrapperCol="{ span: 16 }"
        name="factor_form_in_modal">
        <!-- 要素搜索框 -->
        <a-row :gutter="24" style="margin-bottom: 16px">
          <a-col :span="14" :offset="6">
            <a-input v-model:value="elementSearchValue" placeholder="搜索要素（支持英文/中文名称）" prefix="🔍" style="width: 100%" />
          </a-col>
        </a-row>

        <!-- 要素多选列表（优化加载状态展示） -->
        <a-row :gutter="24" style="margin-bottom: 20px">
          <a-col :span="14" :offset="6">
            <a-form-item name="enNames" label="要素英文名称" :rules="[{ required: true, message: '请至少选择一个要素' }]"
              :wrapper-col="{ span: 24 }">
              <div class="element-checkbox-group">
                <!-- 已配置要素提示 -->
                <div v-if="configuredEnNames.length > 0" class="configured-tip">
                  已配置要素：{{ configuredEnNames.length }} 个 | 可选择要素：{{ filteredElementList.length }} 个
                </div>

                <!-- 优化加载状态：全屏遮罩加载 -->
                <div v-if="elementLoading" class="loading-container">
                  <div class="loading-spinner">
                    <a-spin size="large" tip="加载要素中..."></a-spin>
                  </div>
                </div>

                <!-- 无数据提示（优化文案） -->
                <div v-else-if="filteredElementList.length === 0" class="no-data-tip">
                  <div>
                    <a-icon type="frown-o" style="font-size: 24px; margin-bottom: 8px"></a-icon>
                  </div>
                  {{ configuredEnNames.length > 0 ? "该模板已配置所有要素" : "暂无要素数据" }}
                  <div v-if="!elementListLoaded" style="margin-top: 8px;">
                    <a-button type="text" @click="retryLoadElements" style="color: #1890ff;">
                      点击重试
                    </a-button>
                  </div>
                </div>

                <!-- Checkbox列表（一行一个） -->
                <a-checkbox-group v-else v-model:value="factorFormState.enNames" class="checkbox-list">
                  <div v-for="item in filteredElementList" :key="item.enName" class="checkbox-item">
                    <a-checkbox :value="item.enName">
                      <span class="en-name">{{ item.enName }}</span>
                      <span class="cn-name">（{{ item.cnName || '未命名' }}）</span>
                    </a-checkbox>
                  </div>
                </a-checkbox-group>
              </div>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 已选要素预览（保持不变） -->
        <a-row :gutter="24" style="margin-bottom: 20px">
          <a-col :span="14" :offset="6">
            <div style="margin-bottom: 8px; font-weight: 500">
              已选要素（{{ factorFormState.enNames.length }}个）
              <a-button type="text" @click="clearAllSelection" style="margin-left: 16px; color: #f5222d">
                清空选择
              </a-button>
            </div>
            <div class="selected-tags">
              <a-tag v-for="enName in factorFormState.enNames" :key="enName" closable
                @close="removeSingleElement(enName)" style="margin-right: 8px; margin-bottom: 8px">
                {{ enName }} - {{ getElementCnName(enName) }}
              </a-tag>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </a-space>
</template>
  <script lang="ts" setup>
  // base library
  import { LISTHEADER } from "./config";
  import { listQuery, add, edit, del} from "@/api/pmManagement/pmUniqueValidation/pmUniqueValidation";
  import { addFactor,getConfiguredElements  } from "@/api/pmManagement/pmUniqueElement/pmUniqueElement"; // 保留单个新增+新增批量接口
  import { getElementList } from "@/api/pmManagement/pmElementDef/pmElementDef";
  import { fetchChannelList, ChannelItem,filterChannel, filterChannelByName,handleChannelChange} from "@/utils/utils"; // 导入公共方法和接口
  import { onMounted, computed } from "@vue/runtime-core";

  import {
    computed as vueComputed,
    createVNode,
    reactive,
    ref,
    toRaw,
    unref
  } from "vue";
  import { FormInstance, message, Modal } from "ant-design-vue";
  import { ExclamationCircleOutlined} from "@ant-design/icons-vue";
  
  const searchRef = ref<FormInstance>();
  let searchLoading = ref(true);
  const searchFormState: { [propName: string]: any } = reactive({});
  
  const columns = LISTHEADER;
  let pageNum = ref(1);
  let pageSize = ref(10);
  let total = ref(0);
  let data = ref([]);

  // 新增：要素缓存（按渠道ID分组）
  const elementCache = ref<Record<string, ElementItem[]>>({});
  // 新增：标记要素列表是否加载完成（用于重试逻辑）
  const elementListLoaded = ref<boolean>(false);
  // 新增：重试次数限制
  const maxRetryCount = ref<number>(3); 
  // 渠道列表
  const channelList = ref<ChannelItem[]>([]);
  // 加载渠道列表的loading状态
  const channelLoading = ref(false);


  const handleSearch = (values?: any) => {
    searchLoading.value = true;
    console.log("Received values of form: ", values);
    console.log("searchFormState: ", searchFormState);
    let parameter = { ...searchFormState };
    if (values?.current) {
      pageNum.value = values?.current;
      pageSize.value = values?.pageSize;
    } else {
      selectedRowKeys.value = [];
      selectedRows.value = [];
      pageNum.value = 1;
    }
    const requestParameters = Object.assign({}, parameter, {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    });
    console.log("loadData request parameters:", requestParameters);
  
    listQuery(requestParameters).then(
      (res: {
        code: number | string;
        msg: string;
        total: number;
        rows: any;
      }) => {
        console.log("打印完整的返回信息：" + res);
        searchLoading.value = false;
        const { code, msg, total: count, rows } = res;
        console.log("接口编码：" + code);
        console.log("接口信息：" + JSON.stringify(rows, null, 2))
        if (code === 200) {
          data.value = rows;
          total.value = count;
        } else {
          total.value = 0;
          data.value = [];
          pageNum.value = 1;
          message.error(msg);
        }
      }
    );
  };
  type T = any  
  // 模板选择相关
  const selectedRowKeys = ref<string[]>([]);
  const selectedRows = ref<any[]>([]); // 修正：将T改为any，避免类型错误
  const onSelectChange = (changableRowKeys: string[], changableRows: any[]) => {
    console.log("选中的行ID:", selectedRowKeys);
    console.log("选中的行数据:", selectedRows);
    console.log("selectedRowKeys changed: ", changableRowKeys);
    selectedRowKeys.value = changableRowKeys;
    selectedRows.value = changableRows;
  };
  const rowSelection = vueComputed(() => {
    return {
      selectedRowKeys: unref(selectedRowKeys),
      onChange: onSelectChange,
      hideDefaultSelections: false,
    };
  });
  
  // 模板新增/编辑相关
  enum action {
    add = "新增",
    edit = "编辑",
  }
  const currentAction = ref(action.add);
  const visible = ref<boolean>(false);
  const modalTitleRef = ref<HTMLElement>();
  
  interface FormValues {
    id: string;
    tempName: string;
    tempId: string;
    channelId: string;
    channelName: string;
    remarks: string;
  }
  const formRef = ref<FormInstance>();
  const formState = reactive<FormValues>({
    id: "",
    tempName: "",
    tempId: "",
    channelId: "",
    channelName: "",
    remarks: ""
  });
  const formBackup = { ...formState };
  const reset = () => {
    formRef.value?.resetFields();  
    Object.assign(formState, formBackup);
  }
  const showModal = () => {
    reset();
    formState.id = "";
    visible.value = true;
    currentAction.value = action.add;
  };
  const showEditModal = () => {
    if (selectedRowKeys.value.length > 1)
      message.error("仅能选择一条记录进行操作");
    if (selectedRowKeys.value.length === 0)
      message.error("请选择一条记录进行操作");
    if (selectedRowKeys.value.length === 1) {
      currentAction.value = action.edit;
      visible.value = true;
      formRef.value?.resetFields();
      Object.assign(formState, selectedRows.value[0]);
    }
  };
  const handleOk = (e: MouseEvent) => {
    console.log(e);
    formRef.value
      .validateFields()
      .then((values) => {
        console.log("Received values of form: ", values);
        console.log("formState: ", toRaw(formState));
        visible.value = false;
        if (currentAction.value === action.add) {
          add(formState).then((res: { code: number; msg: string; }) => {
            const { code, msg } = res;
            if (code === 200) {
              Modal.success({ title: msg });
              formRef.value?.resetFields();
            } else {
              Modal.error({ title: msg });
            }
            handleSearch();
          });
        }
        if (currentAction.value === action.edit) {
          edit(formState).then((res: { code: number; msg: string; }) => {
            const { code, msg } = res;
            if (code === 200) {
              Modal.success({ title: msg });
              formRef.value?.resetFields();
            } else {
              Modal.error({ title: msg });
            }
            handleSearch();
          });
        }
      })
      .catch((info) => {
        console.log("Validate Failed:", info);
      });
  };
  const showDelete = () => {
    if (selectedRowKeys.value.length === 0){
      message.error("请选择一条记录进行操作");
    } else {
      Modal.confirm({
        title: "请确认是否操作删除?",
        icon: createVNode(ExclamationCircleOutlined),
        okText: "删除",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          console.log("selectedRows: ", toRaw(selectedRows.value[0]).id,selectedRows);
          del(selectedRowKeys.value).then((res: { code: number; msg: string; }) => {
            const { code, msg } = res;
            if (code === 200) {
              Modal.success({ title: msg });
              handleSearch();
            } else {
              Modal.error({ title: msg });
            }
          });
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    }
  };
// ---------------------- 批量配置要素核心修改 ----------------------
// 要素新增弹窗可见性
const factorVisible = ref<boolean>(false);
// 要素表单引用
const factorFormRef = ref<FormInstance>();
// 选中的模板名称（用于弹窗标题）
const selectedTemplateName = ref<string>('');
// 新增：已配置的要素英文名称列表（用于过滤）
const configuredEnNames = ref<string[]>([]);

// 要素表单数据结构（改为多选数组）
interface FactorFormValues {
    id: string;
    enNames: string[]; // 多选：存储多个要素英文名称
    cnName: string;
    elementType: string;
    channelId: string;
    channelName: string;
    tempId: string;
    mapElementEnName: string;
    elementLength: string;       
    remarks: string;
}

// 要素表单初始化数据
const factorFormState = reactive<FactorFormValues>({
    id: "",
    enNames: [], // 初始化为空数组
    cnName: "",
    elementType: "",
    channelId: "",
    channelName: "",
    tempId: "",
    mapElementEnName: "",
    elementLength: "",   
    remarks: ""
});

// 要素类型接口
interface ElementItem {
    enName: string;//要素英文名称
    cnName: string;//要素中文名称
    elementType: string;//要素类型
    mapElementEnName: string;//映射英文名称
    elementLength: string;//要素长度 
}

// 要素列表
const elementList = ref<ElementItem[]>([]);
// 加载要素列表的loading状态
const elementLoading = ref(false);
// 要素搜索关键词
const elementSearchValue = ref<string>("");

// 筛选后的要素列表（支持搜索）
  const filteredElementList = computed(() => {
    let result = elementList.value;

    // 第一步：过滤已配置的要素（核心修改）
    result = result.filter(item => !configuredEnNames.value.includes(item.enName));
    // 第二步：搜索过滤（原有逻辑保留）
    if (elementSearchValue.value) {
      const searchKey = elementSearchValue.value.toLowerCase();
      result = result.filter(item =>
        item.enName.toLowerCase().includes(searchKey) ||
        (item.cnName && item.cnName.toLowerCase().includes(searchKey))
      );
    }

    return result;
  });

  // 要素表单备份（用于重置）
  const factorFormBackup = { ...factorFormState };

  // 重置要素表单
  const resetFactorForm = () => {
    factorFormRef.value?.resetFields();
    Object.assign(factorFormState, factorFormBackup);
    elementList.value = [];
    elementSearchValue.value = "";
  };

  // 打开要素新增弹窗
  const showFactorAddModal = () => {
    // 校验是否选中了模板
    if (selectedRowKeys.value.length === 0) {
      message.error("请先选择一个模板");
      return;
    }
    if (selectedRowKeys.value.length > 1) {
      message.error("仅能选择一个模板进行要素配置");
      return;
    }

    // 重置表单
    resetFactorForm();
    configuredEnNames.value = []; // 重置已配置要素列表

    // 绑定模板信息（公共字段）
    const selectedTemplate = selectedRows.value[0];
    factorFormState.tempId = selectedTemplate.tempId;
    factorFormState.channelId = selectedTemplate.channelId;
    factorFormState.channelName = selectedTemplate.channelName;
    selectedTemplateName.value = selectedTemplate.tempName;

    // 显示弹窗并加载要素列表
    factorVisible.value = true;
    // 优先使用缓存
    if (elementCache.value[factorFormState.channelId]) {
      elementList.value = elementCache.value[factorFormState.channelId];
      elementLoading.value = false;
      elementListLoaded.value = true;
      // 并行查询已配置要素
      fetchConfiguredElements();
    } else {
      // 无缓存：并行请求已配置要素和全量要素
      elementLoading.value = true;
      Promise.all([
        fetchConfiguredElements(),
        fetchElementListWithRetry() // 带重试的要素加载
      ]).finally(() => {
        elementLoading.value = false;
      });
    }
  };

  // 新增：带重试机制的要素加载
  const fetchElementListWithRetry = async (retryCount = 0) => {
    const channelId = factorFormState.channelId;
    const elementParameters = { channelId };

    try {
      const res = await new Promise((resolve, reject) => {
        getElementList(elementParameters).then(resolve).catch(reject);
      });

      const { code, msg, rows } = res as any;
      if (code === 200) {
        elementList.value = rows;
        elementCache.value[channelId] = rows; // 缓存要素列表
        elementListLoaded.value = true;

        // 批量选择时，清空单个要素的映射字段
        factorFormState.cnName = "批量配置无需填写";
        factorFormState.elementType = "批量配置无需填写";
        factorFormState.mapElementEnName = "批量配置无需填写";
        factorFormState.elementLength = "批量配置无需填写";
      } else {
        throw new Error(`获取要素列表失败：${msg}`);
      }
    } catch (error) {
      console.error(`要素加载失败（第${retryCount + 1}次）`, error);

      if (retryCount < maxRetryCount.value) {
        // 重试机制：指数退避（1s, 2s, 4s）
        await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, retryCount)));
        return fetchElementListWithRetry(retryCount + 1);
      } else {
        message.error("要素加载失败，请稍后重试");
        elementList.value = [];
        elementListLoaded.value = false;
      }
    }
  };

  // 新增：重试加载要素
  const retryLoadElements = () => {
    elementLoading.value = true;
    fetchElementListWithRetry().finally(() => {
      elementLoading.value = false;
    });
  };

  // 优化：查询已配置要素（独立函数，支持并行）
  const fetchConfiguredElements = async () => {
    const params = {
      tempId: factorFormState.tempId,
      channelId: factorFormState.channelId,
    };
    console.log("查询已配置要素参数:", params);

    try {
      const res = await new Promise((resolve, reject) => {
        getConfiguredElements(params).then(resolve).catch(reject);
      });

      const { code, rows } = res as any;
      if (code === 200) {
        configuredEnNames.value = rows.map((item: any) => item.enName).filter(Boolean);
        console.log("该模板已配置的要素:", configuredEnNames.value);
      } else {
        message.warning("查询已配置要素失败，将展示全部要素");
        configuredEnNames.value = [];
      }
    } catch (error) {
      message.error("查询已配置要素出错");
      configuredEnNames.value = [];
    }
  };
// 获取要素列表数据
const fetchElementList = async () => {
  const elementParameters = {
    channelId: factorFormState.channelId,  
  };
  console.log("loadData request elementParameters:", elementParameters);

  elementLoading.value = true;
  try {
    getElementList(elementParameters).then(
      (res: {
        code: number | string;
        msg: string;
        total: number;
        rows: any;
      }) => {
        const { code, msg, total: count, rows } = res;
        console.log("要素接口编码：" + code);
        if (code === 200) {
          elementList.value = rows;
          // 批量选择时，清空单个要素的映射字段（避免混淆）
          factorFormState.cnName = "批量配置无需填写";
          factorFormState.elementType = "批量配置无需填写";
          factorFormState.mapElementEnName = "批量配置无需填写";
          factorFormState.elementLength = "批量配置无需填写";
        } else {
          message.error("获取要素列表失败：" + res.msg);
          elementList.value = [];        
        }
      }
    )
  } catch (error) {
    message.error("获取要素列表出错");
    elementList.value = [];
  } finally {
    elementLoading.value = false;
  }
};

// 清空所有选择
const clearAllSelection = () => {
  factorFormState.enNames = [];
};

// 移除单个选中要素
const removeSingleElement = (enName: string) => {
  factorFormState.enNames = factorFormState.enNames.filter(name => name !== enName);
};

// 根据英文名称获取中文名称（用于标签预览）
const getElementCnName = (enName: string) => {
  const element = elementList.value.find(item => item.enName === enName);
  return element?.cnName || "未知要素";
};

// 批量提交要素配置
const handleFactorBatchOk = () => {
  factorFormRef.value
    .validateFields()
    .then((values) => {
      console.log("要素表单提交数据: ", values);
      console.log("factorFormState: ", toRaw(factorFormState));
      
      // 去重处理
      const uniqueEnNames = [...new Set(factorFormState.enNames)];
      if (uniqueEnNames.length === 0) {
        message.warning("请至少选择一个要素");
        return;
      }
      
      // 构建批量提交数据
      const batchData = uniqueEnNames.map(enName => {
        const elementItem = elementList.value.find(item => item.enName === enName);
        return {
          // 公共字段
          channelId: factorFormState.channelId,
          channelName: factorFormState.channelName,
          tempId: factorFormState.tempId,
          // 要素专属字段
          enName: enName,
          cnName: elementItem?.cnName || "",
          elementType: elementItem?.elementType || "",
          mapElementEnName: elementItem?.mapElementEnName || "",
          elementLength: elementItem?.elementLength || "",
          remarks: factorFormState.remarks || "",
        };
      });

      console.log("批量提交数据: ", batchData);
      
      // 优先调用批量接口，如果后端没有批量接口，可循环调用单个新增接口
      // 降级方案：循环调用单个新增接口
        batchLoopAdd(batchData);
    })
    .catch((info) => {
      console.log("要素表单校验失败:", info);
    });
};

// 降级方案：循环调用单个新增接口
const batchLoopAdd = (batchData: any[]) => {
  let successCount = 0;
  let failCount = 0;
  const totalCount = batchData.length;

  batchData.forEach((item, index) => {
    addFactor(item).then((res: { code: number; msg: string; }) => {
      if (res.code === 200) {
        successCount++;
      } else {
        failCount++;
        console.error(`第 ${index+1} 个要素配置失败：`, res.msg);
      }

      // 所有请求完成后提示结果
      if (successCount + failCount === totalCount) {
        Modal.info({
          title: `批量配置结果`,
          content: `成功：${successCount} 个，失败：${failCount} 个`,
        });
        factorVisible.value = false;
        resetFactorForm();
      }
    });
  });
};

  // 优化：页面初始化时预加载常用渠道的要素（可选，根据业务需求调整）
  onMounted(() => {
    searchLoading.value = false;
    // 并行加载渠道、产品列表
    Promise.all([
      fetchChannelList(channelList, channelLoading)
    ]).then(() => {
      // 预加载第一个渠道的要素（如果有渠道数据）
      if (channelList.value.length > 0) {
        const defaultChannelId = channelList.value[0].transChannelCode;
        fetchElementListWithRetry().then(() => {
          elementCache.value[defaultChannelId] = elementList.value;
        });
      }
    });
  });
  </script>
  <script lang="ts">
  import {
    AppstoreAddOutlined,
    FormOutlined,
    DeleteOutlined,
    UsergroupAddOutlined,
  } from "@ant-design/icons-vue";
  
  export default {
    name: "userConfig",
    components: {
      AppstoreAddOutlined,
      FormOutlined,
      DeleteOutlined,
      UsergroupAddOutlined,
    },
  };
  </script>
  
  <style type="less" scoped>
  .ant-table-striped :deep(.table-striped) td {
    background-color: #fafafa;
  }

  /* 已配置要素提示 */
  .configured-tip {
    margin-bottom: 12px;
    padding: 8px;
    background-color: #e6f7ff;
    border-radius: 4px;
    color: #1890ff;
    font-size: 13px;
  }

  /* 要素多选列表样式 */
  .element-checkbox-group {
    width: 100%;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 12px;
    max-height: 300px;
    overflow-y: auto;
  }

  .checkbox-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .checkbox-item {
    display: flex;
    align-items: center;
    padding: 4px 8px;
    border-radius: 4px;
    transition: background-color 0.2s;

    &:hover {
      background-color: #f5f5f5;
    }
  }

  .en-name {
    font-weight: 500;
    margin-right: 8px;
  }

  .cn-name {
    color: #666;
    font-size: 13px;
  }

  /* 加载中/无数据提示 */
  .loading-tip,
  .no-data-tip {
    text-align: center;
    padding: 20px;
    color: #999;
    font-size: 14px;
  }

  /* 已选要素标签样式 */
  .selected-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    padding: 8px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    background-color: #f9f9f9;
  }

  /* 只读输入框样式优化 */
  :deep(.ant-input[readonly]) {
    background-color: #f5f5f5;
    cursor: not-allowed;
  }

  /* 搜索框样式 */
  :deep(.ant-input-prefix) {
    color: #999;
  }

  /* 弹窗滚动样式 */
  :deep(.ant-modal-body) {
    padding: 24px;
  }
</style>